package com.example.redisrabbitesintegeation.mq;

import com.example.redisrabbitesintegeation.common.config.RabbitConfig;
import com.example.redisrabbitesintegeation.model.entity.News;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName Consumer
 * @Description 消费者
 * @Author Kx
 * @Date 2025/10/21 19:26
 * @Version 1.0
 */
@Slf4j
@Component
public class Consumer {
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConfig.NEWS_CREATE_QUEUE, durable = "true"),
            exchange = @Exchange(name = RabbitConfig.NEWS_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = RabbitConfig.NEWS_CREATE_ROUTING_KEY
    ))
    public void receiveMessage(News news) {
        // 创建 Elasticsearch 文档对象
        com.example.redisrabbitesintegeation.model.document.News newsDocument = new com.example.redisrabbitesintegeation.model.document.News();
        newsDocument.setNewsId(news.getNewsId());
        newsDocument.setTitle(news.getTitle());
        newsDocument.setAuthor(news.getAuthor());
        newsDocument.setClassify(news.getClassify());
        newsDocument.setText(news.getText());
        newsDocument.setCreatedTime(new Date());

        // 添加文档信息
        elasticsearchOperations.save(newsDocument);
        log.info("接收到消息：{}", news);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConfig.NEWS_DELETE_ROUTING_KEY, durable = "true"),
            exchange = @Exchange(name = RabbitConfig.NEWS_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = RabbitConfig.NEWS_DELETE_ROUTING_KEY
    ))
    public void receiveMessage(String newsId) {
        // 删除文档信息
        elasticsearchOperations.delete(newsId, com.example.redisrabbitesintegeation.model.document.News.class);
        log.info("接收到消息：{}", newsId);
    }
}
